<%@ page isELIgnored="true"  language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>教师管理系统</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.8/dist/chart.umd.min.js"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">

    <!-- Tailwind配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#0FC6C2',
                        accent: '#722ED1',
                        warning: '#FF7D00',
                        danger: '#F53F3F',
                        success: '#00B42A',
                        info: '#86909C',
                        light: '#F2F3F5',
                        dark: '#1D2129',
                    },
                    fontFamily: {
                        inter: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </script>

    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .sidebar-icon {
                @apply relative flex items-center justify-center h-10 w-10 mt-2 mb-2 mx-auto
                bg-gray-800 hover:bg-primary hover:text-white
                rounded-3xl hover:rounded-xl
                transition-all duration-300 ease-linear
                cursor-pointer shadow-lg;
            }
            .sidebar-tooltip {
                @apply absolute w-auto p-2 m-2 min-w-max left-14 rounded-md shadow-md
                text-white bg-gray-900
                text-xs font-bold
                transition-all duration-100 scale-0 origin-left;
            }
            .btn-primary {
                @apply bg-primary hover:bg-primary/90 text-white font-medium py-2 px-4 rounded-lg transition-all duration-200;
            }
            .btn-secondary {
                @apply bg-gray-200 hover:bg-gray-300 text-gray-800 font-medium py-2 px-4 rounded-lg transition-all duration-200;
            }
            .btn-danger {
                @apply bg-danger hover:bg-danger/90 text-white font-medium py-2 px-4 rounded-lg transition-all duration-200;
            }
            .btn-warning {
                @apply bg-warning hover:bg-warning/90 text-white font-medium py-2 px-4 rounded-lg transition-all duration-200;
            }
            .btn-success {
                @apply bg-success hover:bg-success/90 text-white font-medium py-2 px-4 rounded-lg transition-all duration-200;
            }
            .card {
                @apply bg-white rounded-xl shadow-md p-5 transition-all duration-300 hover:shadow-lg;
            }
            .input-field {
                @apply w-full px-4 py-2 mt-2 mb-4 text-gray-700 bg-white border border-gray-300 rounded-lg focus:border-primary focus:ring-2 focus:ring-primary/20 transition-all duration-200 outline-none;
            }
            .table-row {
                @apply transition-all duration-200 hover:bg-gray-50;
            }
            .badge {
                @apply px-2 py-1 text-xs rounded-full font-medium;
            }
        }
    </style>
</head>
<body class="bg-gray-100 font-inter antialiased text-gray-800">
<div class="flex h-screen overflow-hidden">
    <!-- 侧边栏导航 -->
    <div class="hidden md:flex md:flex-col md:w-64 md:fixed md:inset-y-0 bg-dark border-r border-gray-800 z-30 transition-all duration-300 ease-in-out" id="sidebar">
        <!-- 教师信息 -->
        <div class="flex items-center justify-center h-16 border-b border-gray-800">
            <div class="flex items-center">
                <div class="h-10 w-10 rounded-full bg-primary flex items-center justify-center">
                    <i class="fa fa-user-circle text-white text-xl"></i>
                </div>
                <div class="ml-3">
                    <p class="text-white font-semibold" id="teacher-name">加载中...</p>
                    <p class="text-gray-400 text-xs" id="teacher-title">加载中...</p>
                </div>
            </div>
        </div>

        <!-- 导航菜单 -->
        <nav class="flex-1 overflow-y-auto py-4 px-3">
            <div class="space-y-1">
                <a href="#dashboard" class="flex items-center px-3 py-2 text-sm font-medium rounded-lg bg-primary/10 text-primary group">
                    <i class="fa fa-tachometer w-5 h-5 mr-3"></i>
                    <span>控制面板</span>
                </a>
                <a href="#exam" class="flex items-center px-极3 py-2 text-sm font-medium rounded-lg text-gray-300 hover:bg-gray-700 hover:text-white group">
                    <i class="fa fa-file-text-o w-5 h-5 mr-3"></i>
                    <span>考试管理</span>
                </a>
                <a href="#students" class="flex items-center px-3 py-2 text-sm font-medium rounded-lg text-gray-300 hover:bg-gray-700 hover:text-white group">
                    <i class="fa fa-user-circle w-5 h-5 mr-3"></i>
                    <span>学生管理</span>
                </a>
                <a href="#grades" class="flex items-center px-3 py-2 text-sm font-medium rounded-lg text-gray-300 hover:bg-gray-700 hover:text-white group">
                    <i class="fa fa-bar-chart w-5 h-5 mr-3"></i>
                    <span>成绩管理</span>
                </a>
                <a href="#account" class="flex items-center px-3 py-2 text-sm font-medium rounded-lg text-gray-300 hover:bg-gray-700 hover:text-white group">
                    <i class="fa fa-user w-5 h-5 mr-3"></i>
                    <span>账户管理</span>
                </a>
            </div>
        </nav>

        <!-- 退出登录 -->
        <div class="border-t border-gray-800 p-4">
            <a href="TeacherLogoutServlet" class="flex items-center px-3 py-2 text-sm font-medium rounded-lg text-gray-300 hover:bg-gray-700 hover:text-white group">
                <i class="fa fa-sign-out w-5 h-5 mr-3"></i>
                <span>退出登录</span>
            </a>
        </div>
    </div>

    <!-- 移动端侧边栏按钮 -->
    <div class="md:hidden fixed top-4 left-4 z-50">
        <button id="sidebar-toggle" class="p-2 rounded-md text-gray-600 hover:text-white hover:bg-primary focus:outline-none">
            <i class="fa fa-bars text-xl"></i>
        </button>
    </div>

    <!-- 主内容区域 -->
    <div class="flex-1 flex flex-col overflow-hidden ml-0 md:ml-64 transition-all duration-300 ease-in-out">
        <!-- 顶部导航栏 -->
        <header class="bg-white shadow-sm z-20">
            <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                <div class="flex justify-between h-16">
                    <div class="flex items-center">
                        <div class="flex-shrink-0 flex items-center">
                            <h1 class="text-xl font-semibold text-primary">教师管理系统</h1>
                        </div>
                    </div>
                    <div class="flex items-center">
                        <div class="flex-shrink-0">
                            <button id="change-password-btn" class="bg-gray-100 hover:bg-gray-200 text-gray-700 font-medium py-2 px-4 rounded-lg transition-all duration-200 flex items-center">
                                <i class="fa fa-key mr-2"></i> 修改密码
                            </button>
                        </div>
                        <div class="ml-4 flex items-center md:ml-6">
                            <button class="p-1 rounded-full text-gray-500 hover:text-primary focus:outline-none">
                                <span class="sr-only">查看通知</span>
                                <i class="fa fa-bell-o text-xl"></i>
                            </button>
                            <div class="ml-3 relative">
                                <div class="flex items-center">
                                    <div class="h-8 w-8 rounded-full bg-primary flex items-center justify-center">
                                        <i class="fa fa-user text-white"></i>
                                    </div>
                                    <span class="ml-2 text-sm font-medium text-gray-700 hidden md:block" id="top-teacher-name">加载中...</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </header>

        <!-- 页面内容 -->
        <main class="flex-1 overflow-y-auto bg-gray-100 p-4 sm:p-6 lg:p极8">
            <!-- 控制面板 -->
            <section id="dashboard-section" class="space-y-6">
                <div class="flex flex-col md:flex-row md:items-center md:justify-between">
                    <div>
                        <h2 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-gray-900">控制面板</h2>
                        <p class="mt-1 text-sm text-gray-500" id="welcome-message">欢迎回来，请稍候...</p>
                    </div>
                    <div class="mt-4 flex md:mt-0 md:ml-4">
                        <button type="button" class="btn-secondary" id="refresh-dashboard">
                            <i class="fa fa-refresh mr-2"></i> 刷新数据
                        </button>
                    </div>
                </div>

                <!-- 数据概览卡片 -->
                <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6" id="dashboard-cards">
                    <!-- 卡片内容将通过AJAX填充 -->
                </div>

                <!-- 图表区域 -->
                <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                    <div class="card lg:col-span-2">
                        <div class="flex items-center justify-between mb-6">
                            <h3 class="text-lg font-semibold text-gray-900">近期考试安排</h3>
                            <div class="flex space-x-2">
                                <button class="px-3 py-1 text-sm rounded-md bg-primary/10 text-primary">本周</button>
                                <button class="px-3 py-1 text-sm rounded-md bg-gray-100 text-gray-700 hover:bg-gray-200">本月</button>
                                <button class="px-3 py-1 text-sm rounded-md bg-gray-100 text-gray-700 hover:bg-gray-200">本学期</button>
                            </div>
                        </div>
                        <div class="h-80">
                            <canvas id="examScheduleChart"></canvas>
                        </div>
                    </div>

                    <div class="card">
                        <div class="flex items-center justify-between mb-6">
                            <h3 class="text-lg font-semibold text-gray-900">任教课程分布</h3>
                            <button class="text-gray-400 hover:text-gray-600">
                                <i class="fa fa-ellipsis-v"></i>
                            </button>
                        </div>
                        <canvas id="courseDistributionChart"></canvas>
                    </div>
                </div>
            </section>

            <!-- 考试管理模块 -->
            <section id="exam-section" class="hidden space-y-6">
                <div class="flex flex-col md:flex-row md:items-center md:justify-between">
                    <div>
                        <h2 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-gray-900">考试管理</h2>
                        <p class="mt-1 text-sm text-gray-500">申请和管理考试安排</p>
                    </div>
                    <div class="mt-4 flex md:mt-0 md:ml-4">
                        <button id="apply-exam-btn" class="btn-primary">
                            <i class="fa fa-plus mr-2"></i> 申请考试
                        </button>
                    </div>
                </div>

                <!-- 考试列表 -->
                <div class="card">
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-gray-200">
                            <thead class="bg-gray-50">
                            <tr>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">考试名称</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">课程</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">班级</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">考试时间</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                                <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                            </tr>
                            </thead>
                            <tbody id="exam-list" class="bg-white divide-y divide-gray-200">
                            <!-- 考试列表将通过AJAX填充 -->
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- 申请考试表单 -->
                <div id="apply-exam-form" class="card hidden">
                    <h3 class="text-lg font-medium text-gray-900 mb-6">申请新考试</h3>
                    <form id="exam-application-form">
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">考试名称</label>
                                <input type="text" name="exam-name" class="input-field" placeholder="例如：期中考试" required>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">考试课程</label>
                                <select id="exam-course" name="exam-course" class="input-field" required>
                                    <option value="">请选择课程</option>
                                    <!-- 课程选项将通过AJAX填充 -->
                                </select>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">考试日期</label>
                                <input type="date" name="exam-date" class="input-field" required>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">开始时间</label>
                                <input type="time" name="exam-time" class="input-field" required>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">考试时长(分钟)</label>
                                <input type="number" name="exam-duration" class="input-field" placeholder="例如：120" min="30" required>
                            </div>
                            <div class="md:col-span-2">
                                <label class="block text-sm font-medium text-gray-700 mb-1">考试班级</label>
                                <div id="class-checkboxes" class="grid grid-cols-2 md:grid-cols-3 gap-3">
                                    <!-- 班级复选框将通过AJAX填充 -->
                                </div>
                            </div>
                            <div class="md:col-span-2">
                                <label class="block text-sm font-medium text-gray-700 mb-1">考试说明</label>
                                <textarea name="exam-description" class="input-field" rows="3" placeholder="请输入考试说明..."></textarea>
                            </div>
                        </div>
                        <div class="flex justify-end space-x-3 mt-6">
                            <button type="button" id="cancel-apply-btn" class="btn-secondary">取消</button>
                            <button type="submit" class="btn-primary">提交申请</button>
                        </div>
                    </form>
                </div>
            </section>

            <!-- 学生管理模块 -->
            <section id="students-section" class="hidden space-y-6">
                <div class="flex flex-col md:flex-row md:items-center md:justify-between">
                    <div>
                        <h2 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text极gray-900">学生管理</h2>
                        <p class="mt-1 text-sm text-gray-500">查看和管理学生信息</p>
                    </div>
                </div>

                <!-- 班级选择 -->
                <div class="card">
                    <div class="flex flex-col md:flex-row md:items-center md:justify-between space-y-4 md:space-y-0">
                        <div class="flex-1">
                            <label class="block text-sm font-medium text-gray-700 mb-2">选择班级查看学生</label>
                            <div id="class-buttons" class="flex flex-wrap gap-3">
                                <!-- 班级按钮将通过AJAX填充 -->
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 学生列表 -->
                <div class="card">
                    <div class="flex justify-between items-center mb-4">
                        <h3 id="class-name-title" class="text-lg font-medium text-gray-900">请选择班级</h3>
                        <div class="flex items-center">
                            <div class="relative mr-2">
                                <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                    <i class="fa fa-search text-gray-400"></i>
                                </div>
                                <input type="text" id="student-search" class="pl-10 input-field w-64" placeholder="搜索学生...">
                            </div>
                            <button id="search-btn" class="btn-primary">
                                <i class="fa fa-search mr-2"></i> 搜索
                            </button>
                        </div>
                    </div>
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-gray-200">
                            <thead class="bg-gray-50">
                            <tr>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">学号</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">姓名</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">性别</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">电话</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                                <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                            </tr>
                            </thead>
                            <tbody id="student-list" class="bg-white divide-y divide-gray-200">
                            <!-- 学生列表将通过AJAX填充 -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </section>

            <!-- 成绩管理模块 -->
            <section id="grades-section" class="hidden space-y-6">
                <div class="flex flex-col md:flex-row md:items-center md:justify-between">
                    <div>
                        <h2 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-gray-900">成绩管理</h2>
                        <p class="mt-1 text-sm text-gray-500">查看和分析学生成绩</p>
                    </div>
                </div>

                <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                    <div class="card">
                        <h3 class="text-lg font-medium text-gray-900 mb-4">按班级查询成绩</h3>
                        <div class="space-y-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">选择班级</label>
                                <select id="grade-class" class="input-field" required>
                                    <option value="">请选择班级</option>
                                    <!-- 班级选项将通过AJAX填充 -->
                                </select>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">选择考试</label>
                                <select id="grade-exam" class="input-field" required>
                                    <option value="">请选择考试</option>
                                </select>
                            </div>
                            <button id="view-class-grades" class="btn-primary w-full">查看班级成绩</button>
                        </div>
                    </div>

                    <div class="card">
                        <h3 class="text-lg font-medium text-gray-900 mb-4">按学生查询成绩</h3>
                        <div class="space-y-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">学生姓名/学号</label>
                                <input type="text" id="student-search-grade" class="input-field" placeholder="输入学生姓名或学号">
                            </div>
                            <button id="view-student-grades" class="btn-primary w-full">查询学生成绩</button>
                        </div>
                    </div>
                </div>

                <!-- 成绩显示区域 -->
                <div class="card hidden" id="grades-result">
                    <div class="flex justify-between items-center mb-4">
                        <h3 id="grades-title" class="text-lg font-medium text-gray-900"></h3>
                        <button id="export-grades" class="btn-secondary">
                            <i class="fa fa-download mr-2"></i> 导出成绩
                        </button>
                    </div>
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-gray-200">
                            <thead class="bg-gray-50">
                            <tr id="grades-header">
                                <!-- 表头将通过AJAX填充 -->
                            </tr>
                            </thead>
                            <tbody id="grades-body" class="bg-white divide-y divide-gray-200">
                            <!-- 成绩数据将通过AJAX填充 -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </section>

            <!-- 账户管理模块 -->
            <section id="account-section" class="hidden space-y-6">
                <div class="flex flex-col md:flex-row md:items-center md:justify-between">
                    <div>
                        <h2 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-gray-900">账户管理</h2>
                        <p class="mt-1 text-sm text-gray-500">管理您的账户信息和安全设置</p>
                    </div>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <!-- 个人信息 -->
                    <div class="card">
                        <h3 class="text-lg font-medium text-gray-900 mb-4">个人信息</h3>
                        <form id="profile-form" method="POST" action="ProfileUpdateServlet">
                            <div class="space-y-4">
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">教师编号</label>
                                    <input type="text" id="teacher_no" class="input-field bg-gray-100" disabled>
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">姓名</label>
                                    <input type="text" id="teacher_name" class="input-field bg-gray-100" disabled>
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">职称</label>
                                    <input type="text" name="title" id="title" class="input-field">
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">电话</label>
                                    <input type="tel" name="phone" id="phone" class="input-field">
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">邮箱</label>
                                    <input type="email" name="email" id="email" class="input-field">
                                </div>
                                <button type="submit" class="btn-primary w-full">更新个人信息</button>
                            </div>
                        </form>
                    </div>

                    <!-- 修改密码 -->
                    <div class="card">
                        <h3 class="text-lg font-medium text-gray-900 mb-4">修改密码</h3>
                        <form id="password-form">
                            <div class="space-y-4">
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">当前密码</label>
                                    <input type="password" name="current-password" class="input-field" placeholder="请输入当前密码" required>
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">新密码</label>
                                    <input type="password" name="new-password" class="input-field" placeholder="请输入新密码" required>
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">确认新密码</label>
                                    <input type="password" name="confirm-password" class="input-field" placeholder="请再次输入新密码" required>
                                </div>
                                <div class="text-sm text-gray-500">
                                    <p>密码要求：</p>
                                    <ul class="list-disc pl-5 mt-1">
                                        <li>至少8个字符</li>
                                        <li>包含字母和数字</li>
                                        <li>可包含特殊字符</li>
                                    </ul>
                                </div>
                                <button type="submit" class="btn-primary w-full">修改密码</button>
                            </div>
                        </form>
                    </div>
                </div>
            </section>
        </main>
    </div>
</div>

<!-- 修改密码模态框 -->
<div id="change-password-modal" class="fixed inset-0 bg-black bg-opacity-50 z-50 hidden">
    <div class="min-h-screen flex items-center justify-center p-4">
        <div class="bg-white rounded-lg max-w-md w-full mx-auto p-6 transform transition-all">
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-lg font-medium text-gray-900">修改密码</h3>
                <button id="close-password-modal" class="text-gray-400 hover:text-gray-500">
                    <i class="fa fa-times"></i>
                </button>
            </div>
            <form id="modal-password-form">
                <div class="mb-4">
                    <label for="current-password" class="block text-sm font-medium text-gray-700">当前密码</label>
                    <input type="password" id="current-password" name="current-password" class="input-field" required>
                </div>
                <div class="mb-4">
                    <label for="new-password" class="block text-sm font-medium text-gray-700">新密码</label>
                    <input type="password" id="new-password" name="new-password" class="input-field" required>
                </div>
                <div class="mb-6">
                    <label for="confirm-password" class="block text-sm font-medium text-gray-700">确认新密码</label>
                    <input type="password" id="confirm-password" name="confirm-password" class="input-field" required>
                </div>
                <div class="flex justify-end space-x-3">
                    <button type="button" id="cancel-password-btn" class="btn-secondary">取消</button>
                    <button type="submit" class="btn-primary">修改密码</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 通知提示 -->
<div id="notification" class="fixed top-4 right-4 max-w-sm w-full bg-white rounded-lg shadow-lg p-4 transform transition-all duration-300 translate-x-full z-50 flex items-start">
    <div id="notification-icon" class="flex-shrink-0 h-6 w-6 flex items-center justify-center rounded-full bg-green-100 text-green-500">
        <i class="fa fa-check"></i>
    </div>
    <div class="ml-3">
        <h3 id="notification-title" class="text-sm font-medium text-gray-900">操作成功</h3>
        <div id="notification-message" class="mt-1 text-sm text-gray-500">
            您的操作已成功完成。
        </div>
    </div>
    <button id="close-notification" class="ml-auto flex-shrink-0 text-gray-400 hover:text-gray-600">
        <i class="fa fa-times"></i>
    </button>
</div>

<script>
    // 全局变量
    let currentClassId = null;
    let courses = [];
    let classes = [];

    // 页面初始化
    document.addEventListener('DOMContentLoaded', function() {
        // 初始化数据
        loadDashboardData();
        loadExamList();
        loadCourses();
        loadClasses();
        loadTeacherProfile(); // 加载教师个人信息

        // 侧边栏切换
        document.getElementById('sidebar-toggle').addEventListener('click', function() {
            const sidebar = document.querySelector('.md\\:flex');
            sidebar.classList.toggle('hidden');
        });

        // 导航菜单切换
        const navLinks = document.querySelectorAll('nav a');
        navLinks.forEach(link => {
            link.addEventListener('click', function(e) {
                e.preventDefault();

                // 获取目标部分
                const target = this.getAttribute('href').substring(1);
                const sections = document.querySelectorAll('main > section');

                // 隐藏所有部分
                sections.forEach(section => {
                    section.classList.add('hidden');
                });

                // 显示目标部分
                document.getElementById(target + '-section').classList.remove('hidden');

                // 更新活动链接样式
                navLinks.forEach(l => l.classList.remove('bg-primary/10', 'text-primary'));
                this.classList.add('bg-primary/10', 'text-primary');

                // 加载特定部分的数据
                if (target === 'students' && classes.length > 0 && !currentClassId) {
                    // 默认选择第一个班级
                    selectClass(classes[0].class_id, classes[0].class_name);
                } else if (target === 'grades') {
                    // 加载成绩管理所需的数据
                    loadGradeClasses();
                }
            });
        });

        // 考试申请按钮
        document.getElementById('apply-exam-btn').addEventListener('click', function() {
            document.getElementById('apply-exam-form').classList.remove('hidden');
            this.classList.add('hidden');
        });

        // 取消考试申请按钮
        document.getElementById('cancel-apply-btn').addEventListener('click', function() {
            document.getElementById('apply-exam-form').classList.add('hidden');
            document.getElementById('apply-exam-btn').classList.remove('hidden');
        });

        // 考试申请表单提交
        document.getElementById('exam-application-form').addEventListener('submit', function(e) {
            e.preventDefault();
            applyForExam();
        });

        // 学生搜索按钮
        document.getElementById('search-btn').addEventListener('click', function() {
            searchStudents();
        });

        // 学生搜索输入框回车键
        document.getElementById('student-search').addEventListener('keyup', function(e) {
            if (e.key === 'Enter') {
                searchStudents();
            }
        });

        // 刷新仪表盘数据
        document.getElementById('refresh-dashboard').addEventListener('click', function() {
            loadDashboardData();
        });

        // 个人信息更新
        document.getElementById('profile-form').addEventListener('submit', function(e) {
            e.preventDefault();
            updateProfile();
        });

        // 密码修改表单提交
        document.getElementById('password-form').addEventListener('submit', function(e) {
            e.preventDefault();
            changePassword('password-form');
        });

        // 模态框表单提交
        document.getElementById('modal-password-form').addEventListener('submit', function(e) {
            e.preventDefault();
            changePassword('modal-password-form');
        });

        // 成绩管理 - 班级选择变化
        document.getElementById('grade-class').addEventListener('change', function() {
            loadExamsForClass(this.value);
        });

        // 查看班级成绩
        document.getElementById('view-class-grades').addEventListener('click', function() {
            const classId = document.getElementById('grade-class').value;
            const examId = document.getElementById('grade-exam').value;

            if (!classId || !examId) {
                showNotification('错误', '请选择班级和考试', 'danger');
                return;
            }

            viewClassGrades(classId, examId);
        });

        // 查看学生成绩
        document.getElementById('view-student-grades').addEventListener('click', function() {
            const keyword = document.getElementById('student-search-grade').value;

            if (!keyword) {
                showNotification('错误', '请输入学生姓名或学号', 'danger');
                return;
            }

            viewStudentGrades(keyword);
        });

        // 模态框事件处理
        setupModalEvents();
    });

    // 加载仪表盘数据
    function loadDashboardData() {
        fetch('TeacherDashboardDataServlet')
            .then(response => response.json())
            .then(data => {
                // 更新卡片数据
                document.getElementById('dashboard-cards').innerHTML = `
                    <div class="card">
                        <div class="flex items-center">
                            <div class="flex-shrink-0 bg-blue-100 p-3 rounded-full">
                                <i class="fa fa-book text-primary text-xl"></i>
                            </div>
                            <div class="ml-5 w-0 flex-1">
                                <dl>
                                    <dt class="text-sm font-medium text-gray-500 truncate">任教课程</dt>
                                    <dd>
                                        <div class="text-lg font-semib极old text-gray-900">
                                            <span id="course-count">${data.courseCount}</span>
                                        </div>
                                    </dd>
                                </dl>
                            </div>
                        </div>
                    </div>
                    <div class="card">
                        <div class="flex items-center">
                            <div class="flex-shrink-0 bg-green-100 p-3 rounded-full">
                                <i class="fa fa-graduation-cap text-success text-xl"></i>
                            </div>
                            <div class="ml-5 w-0 flex-1">
                                <dl>
                                    <dt class="text-sm font-medium text-gray-500 truncate">负责班级</dt>
                                    <dd>
                                        <div class="text-lg font-semibold text-gray-900">
                                            <span id="class-count">${data.studentCount ? data.studentCount : 0}</span>
                                        </极div>
                                    </dd>
                                </dl>
                            </div>
                        </div>
                    </div>
                    <div class="card">
                        <div class="flex items-center">
                            <div class="flex-shrink-0 bg-purple-100 p-3 rounded-full">
                                <i class="fa fa-users text-accent text-xl"></i>
                            </div>
                            <div class="ml-5 w-0 flex-1">
                                <dl>
                                    <dt class="text-sm font-medium text-gray-500 truncate">学生总数</dt>
                                    <dd>
                                        <div class="text-lg font-semibold text-gray-900">
                                            <span id="student-count">${data.studentCount}</span>
                                        </div>
                                    </dd>
                                </dl>
                            </div>
                        </div>
                    </div>
                    <div class="card">
                        <div class="flex items-center">
                            <div class="flex-shrink-0 bg-orange-100 p-3 rounded-full">
                                <i class="fa fa-file-text-o text-warning text-xl"></i>
                            </div>
                            <div class="ml-5 w-0 flex-1">
                                <dl>
                                    <dt class="text-sm font-medium text-gray-500 truncate">待批改试卷</dt>
                                    <dd>
                                        <div class="text-lg font-semibold text-gray-900">
                                            <span id="pending-count">${data.pendingCount}</span>
                                        </div>
                                    </dd>
                                </dl>
                            </div>
                        </div>
                    </div>
                `;

                // 初始化图表
                initCharts(data);
            })
            .catch(error => {
                console.error('加载仪表盘数据失败:', error);
                showNotification('错误', '加载仪表盘数据失败', 'danger');
            });
    }

    // 加载考试列表
    function loadExamList() {
        fetch('ExamListServlet')
            .then(response => response.json())
            .then(exams => {
                const examList = document.getElementById('exam-list');
                examList.innerHTML = '';

                exams.forEach(exam => {
                    const statusText = getStatusText(exam.status);
                    const statusClass = getStatusClass(exam.status);

                    const row = document.createElement('tr');
                    row.className = 'table-row';
                    row.innerHTML = `
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm font-medium text-gray-900">${exam.exam_name}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-500">${exam.course_name}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-500">${exam.class_names}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-500">${exam.start_time}</div>
                            <div class="text-sm text-gray-500">${exam.duration}分钟</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="px-2 py-1 text-xs rounded-full ${statusClass}">${statusText}</span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                            <button class="text-primary hover:text-primary/80 mr-3 view-exam" data-id="${exam.exam_id}">查看</button>
                            ${exam.status == 0 ?
                                '<button class="text-danger hover:text-danger/80 cancel-exam" data-id="' + exam.exam_id + '">取消</button>'
                                : '<button class="text-gray-400 cursor-not-allowed" disabled>取消</button>'}
                        </td>
                    `;
                    examList.appendChild(row);
                });

                // 修复：添加事件监听器到取消和查看按钮
                document.querySelectorAll('#exam-list .cancel-exam').forEach(button => {
                    button.addEventListener('click', function() {
                        const examId = this.getAttribute('data-id');
                        cancelExam(examId);
                    });
                });

                document.querySelectorAll('#exam-list .view-exam').forEach(button => {
                    button.addEventListener('click', function() {
                        const examId = this.getAttribute('data-id');
                        viewExamDetails(examId);
                    });
                });
            })
            .catch(error => {
                console.error('加载考试列表失败:', error);
                showNotification('错误', '加载考试列表失败', 'danger');
            });
    }

    // 查看考试详情
    function viewExamDetails(examId) {
        fetch(`ExamDetailServlet?exam_id=${examId}`)
            .then(response => response.json())
            .then(data => {
                // 这里可以显示考试详情，例如在模态框中
                alert(`考试名称: ${data.exam_name}\n课程: ${data.course_name}\n时间: ${data.start_time} 至 ${data.end_time}\n班级: ${data.class_names}\n状态: ${getStatusText(data.status)}`);
            })
            .catch(error => {
                console.error('获取考试详情失败:', error);
                showNotification('错误', '获取考试详情失败', 'danger');
            });
    }

    // 取消考试
    function cancelExam(examId) {
        if (confirm('确定要取消这个考试吗？此操作不可撤销。')) {
            fetch(`ExamCancelServlet?exam_id=${examId}`, { method: 'GET' })
                .then(response => {
                    if (response.ok) {
                        showNotification('成功', '考试已取消', 'success');
                        loadExamList(); // 刷新考试列表
                    } else {
                        showNotification('错误', '取消失败', 'danger');
                    }
                })
                .catch(error => {
                    console.error('取消考试失败:', error);
                    showNotification('错误', '取消考试失败', 'danger');
                });
        }
    }

    // 加载课程列表
    function loadCourses() {
        fetch('CourseListServlet')
            .then(response => response.json())
            .then(data => {
                courses = data;
                const courseSelect = document.getElementById('exam-course');
                courseSelect.innerHTML = '<option value="">请选择课程</option>';

                data.forEach(course => {
                    const option = document.createElement('option');
                    option.value = course.course_id;
                    option.textContent = course.course_name;
                    courseSelect.appendChild(option);
                });
            })
            .catch(error => {
                console.error('加载课程列表失败:', error);
                showNotification('错误', '加载课程列表失败', 'danger');
            });
    }

    // 加载班级列表
    function loadClasses() {
        fetch('ClassListServlet')
            .then(response => response.json())
            .then(data => {
                classes = data;

                // 更新班级按钮
                const classButtons = document.getElementById('class-buttons');
                classButtons.innerHTML = '';

                data.forEach(cls => {
                    const button = document.createElement('button');
                    button.className = 'px-4 py-2 bg-gray-200 hover:bg-gray-300 text-gray-800 rounded-lg class-button';
                    button.textContent = cls.class_name;
                    button.setAttribute('data-class-id', cls.class_id);
                    button.addEventListener('click', () => {
                        selectClass(cls.class_id, cls.class_name);
                    });
                    classButtons.appendChild(button);
                });

                // 更新考试申请表单中的班级复选框
                const classCheckboxes = document.getElementById('class-checkboxes');
                classCheckboxes.innerHTML = '';

                data.forEach(cls => {
                    const label = document.createElement('label');
                    label.className = 'flex items-center';
                    label.innerHTML = `
                        <input type="checkbox" name="exam-class" value="${cls.class_id}" class="rounded border-gray-300 text-primary focus:ring-primary">
                        <span class="ml-2 text-sm text-gray-700">${cls.class_name}</span>
                    `;
                    classCheckboxes.appendChild(label);
                });
            })
            .catch(error => {
                console.error('加载班级列表失败:', error);
                showNotification('错误', '加载班级列表失败', 'danger');
            });
    }

    // 选择班级
    function selectClass(classId, className) {
        currentClassId = classId;
        document.getElementById('class-name-title').textContent = `${className} - 学生列表`;

        // 高亮选中的班级按钮
        document.querySelectorAll('.class-button').forEach(button => {
            if (button.getAttribute('data-class-id') == classId) {
                button.classList.remove('bg-gray-200');
                button.classList.add('bg-primary', 'text-white');
            } else {
                button.classList.remove('bg-primary', 'text-white');
                button.classList.add('bg-gray-200');
            }
        });

        // 加载学生列表
        loadStudents(classId);
    }

    // 加载学生列表
    function loadStudents(classId) {
        fetch(`ClassStudentsServlet?classId=${classId}`)
            .then(response => response.json())
            .then(students => {
                const studentList = document.getElementById('student-list');
                studentList.innerHTML = '';

                students.forEach(student => {
                    // 确保正确解析状态值
                    const statusText = student.status === 1 ? '在读' : '休学';
                    const statusClass = student.status === 1 ? 'bg-success text-white' : 'bg-warning text-white';

                    const row = document.createElement('tr');
                    row.className = 'table-row';
                    row.innerHTML = `
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm font-medium text-gray-900">${student.student_no}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-900">${student.name}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-500">${student.gender}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-500">${student.phone}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="px-2 py-1 text-xs rounded-full ${statusClass}">${statusText}</span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                            <button class="text-primary hover:text-primary/80" data-student-id="${student.student_id}">查看详情</button>
                        </td>
                    `;
                    studentList.appendChild(row);
                });

                // 添加学生详情点击事件
                document.querySelectorAll('#student-list .text-primary').forEach(button => {
                    button.addEventListener('click', function() {
                        const studentId = this.getAttribute('data-student-id');
                        viewStudentDetails(studentId);
                    });
                });
            })
            .catch(error => {
                console.error('加载学生列表失败:', error);
                showNotification('错误', '加载学生列表失败', 'danger');
            });
    }

    // 查看学生详情
    function viewStudentDetails(studentId) {
        // 这里可以显示学生详情，例如在模态框中
        alert(`学生ID: ${studentId}\n功能实现中...`);
    }

    // 搜索学生
    function searchStudents() {
        const keyword = document.getElementById('student-search').value;

        if (!currentClassId) {
            showNotification('提示', '请先选择班级', 'info');
            return;
        }

        // 添加班级ID参数
        fetch(`StudentSearchServlet?keyword=${encodeURIComponent(keyword)}&classId=${currentClassId}`)
            .then(response => response.json())
            .then(students => {
                const studentList = document.getElementById('student-list');
                studentList.innerHTML = '';

                if (students.length === 0) {
                    studentList.innerHTML = '<tr><td colspan="6" class="px-6 py-4 text-center text-sm text-gray-500">没有找到匹配的学生</td></tr>';
                    return;
                }

                students.forEach(student => {
                    // 确保正确解析状态值
                    const statusText = student.status === 1 ? '在读' : '休学';
                    const statusClass = student.status === 1 ? 'bg-success text-white' : 'bg-warning text-white';

                    const row = document.createElement('tr');
                    row.className = 'table-row';
                    row.innerHTML = `
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm font-medium text-gray-900">${student.student_no}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-900">${student.name}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-500">${student.gender}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-500">${student.phone}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="px-2 py-1 text-xs rounded-full ${statusClass}">${statusText}</span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                            <button class="text-primary hover:text-primary/80" data-student-id="${student.student_id}">查看详情</button>
                        </td>
                    `;
                    studentList.appendChild(row);
                });

                // 添加学生详情点击事件
                document.querySelectorAll('#student-list .text-primary').forEach(button => {
                    button.addEventListener('click', function() {
                        const studentId = this.getAttribute('data-student-id');
                        viewStudentDetails(studentId);
                    });
                });
            })
            .catch(error => {
                console.error('搜索学生失败:', error);
                showNotification('错误', '搜索学生失败', 'danger');
            });
    }

    // 申请考试
    function applyForExam() {
        // 获取表单元素
        const form = document.getElementById('exam-application-form');

        // 使用传统方式获取参数值
        const examName = form.elements['exam-name'].value;
        const courseId = form.elements['exam-course'].value;
        const examDate = form.elements['exam-date'].value;
        const examTime = form.elements['exam-time'].value;
        const duration = form.elements['exam-duration'].value;
        const description = form.elements['exam-description'].value;

        // 获取选中的班级
        const classCheckboxes = document.querySelectorAll("[name='exam-class']:checked");
        const classIds = Array.from(classCheckboxes).map(cb => cb.value);

        // 验证必填字段
        if (!examName || !courseId || !examDate || !examTime || !duration || classIds.length === 0) {
            let errorMessage = "请填写所有必填字段: ";
            if (!examName) errorMessage += "[考试名称] ";
            if (!courseId) errorMessage += "[课程] ";
            if (!examDate) errorMessage += "[日期] ";
            if (!exam极Time) errorMessage += "[时间] ";
            if (!duration) errorMessage += "[时长] ";
            if (classIds.length === 0) errorMessage += "[班级]";

            showNotification('错误', errorMessage, 'danger');
            return;
        }

        // 使用传统表单提交方式
        const formData = new FormData();
        formData.append("exam-name", examName);
        formData.append("exam-course", courseId);
        formData.append("exam-date", examDate);
        formData.append("exam-time", examTime);
        formData.append("exam-duration", duration);
        formData.append("exam-description", description);

        // 添加所有选中的班级
        classIds.forEach(classId => {
            formData.append("exam-class", classId);
        });

        // 显示加载指示器
        const submitBtn = form.querySelector("button[type='submit']");
        const originalBtnText = submitBtn.innerHTML;
        submitBtn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> 提交中...';
        submitBtn.disabled = true;

        // 使用传统XHR方式提交
        const xhr = new XMLHttpRequest();
        xhr.open('POST', 'ExamApplyServlet', true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

        xhr.onload = function() {
            try {
                if (xhr.status >= 200 && xhr.status < 300) {
                    const response = JSON.parse(xhr.responseText);
                    if (response.success) {
                        showNotification('成功', response.message, 'success');
                        // 重置表单
                        form.reset();
                        document.getElementById('apply-exam-form').classList.add('hidden');
                        document.getElementById('apply-exam-btn').classList.remove('hidden');
                        // 刷新考试列表
                        loadExamList();
                    } else {
                        showNotification('错误', response.message, 'danger');
                    }
                } else {
                    showNotification('错误', '请求失败，状态码: ' + xhr.status, 'danger');
                }
            } catch (e) {
                showNotification('错误', '解析响应失败: ' + e.message, 'danger');
            } finally {
                // 恢复按钮状态
                submitBtn.innerHTML = originalBtnText;
                submitBtn.disabled = false;
            }
        };

        xhr.onerror = function() {
            showNotification('错误', '网络请求失败', 'danger');
            submitBtn.innerHTML = originalBtnText;
            submitBtn.disabled = false;
        };

        // 将FormData转换为URL编码格式
        const urlEncodedData = new URLSearchParams();
        for (const [key, value] of formData.entries()) {
            urlEncodedData.append(key, value);
        }

        xhr.send(urlEncodedData.toString());
    }

    // 加载教师个人信息
    function loadTeacherProfile() {
        fetch('ProfileServlet')
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    // 更新表单字段
                    document.getElementById('teacher_no').value = data.teacher_no || '';
                    document.getElementById('teacher_name').value = data.teacher_name || '';
                    document.getElementById('title').value = data.title || '';
                    document.getElementById('phone').value = data.phone || '';
                    document.getElementById('email').value = data.email || '';

                    // 更新顶部和侧边栏显示
                    document.getElementById('teacher-name').textContent = data.teacher_name;
                    document.getElementById('teacher-title').textContent = data.title || '未设置职称';
                    document.getElementById('top-teacher-name').textContent = data.teacher_name;
                    document.getElementById('welcome-message').textContent = `欢迎回来，${data.teacher_name}！`;

                    // 日志输出
                    console.log('教师信息加载成功:', data);
                } else {
                    showNotification('错误', data.message, 'danger');
                }
            })
            .catch(error => {
                console.error('获取教师信息失败:', error);
                showNotification('错误', '获取教师信息失败', 'danger');
            });
    }

    // 更新个人信息
    function updateProfile() {
        const form = document.getElementById('profile-form');
        const formData = new FormData(form);

        // 确保所有字段都有值
        const title = formData.get('title') || '';
        const phone = formData.get('phone') || '';
        const email = formData.get('email') || '';

        // 添加表单验证
        if (phone && !/^1[3-9]\d{9}$/.test(phone)) {
            showNotification('错误', '请输入有效的手机号码', 'danger');
            return;
        }

        if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
            showNotification('错误', '请输入有效的邮箱地址', 'danger');
            return;
        }

        // 创建新的URLSearchParams对象
        const params = new URLSearchParams();
        params.append('title', title);
        params.append('phone', phone);
        params.append('email', email);

        // 显示加载状态
        const submitBtn = form.querySelector('button[type="submit"]');
        const originalText = submitBtn.innerHTML;
        submitBtn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> 更新中...';
        submitBtn.disabled = true;

        fetch('ProfileUpdateServlet', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: params.toString()
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showNotification('成功', data.message, 'success');
                    // 使用返回的数据更新页面
                    document.getElementById('title').value = data.title || '';
                    document.getElementById('phone').value = data.phone || '';
                    document.getElementById('email').value = data.email || '';
                    // 更新顶部和侧边栏显示
                    document.getElementById('teacher-name').textContent = data.teacher_name;
                    document.getElementById('teacher-title').textContent = data.title || '未设置职称';
                    document.getElementById('top-teacher-name').textContent = data.teacher_name;

                    console.log('个人信息更新成功:', data);
                } else {
                    showNotification('错误', data.message, 'danger');
                }
            })
            .catch(error => {
                console.error('更新个人信息失败:', error);
                showNotification('错误', '更新个人信息失败', 'danger');
            })
            .finally(() => {
                submitBtn.innerHTML = originalText;
                submitBtn.disabled = false;
            });
    }

    // 密码验证函数
    function validatePassword(password) {
        // 密码至少8个字符，包含字母和数字
        const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d).{8,}$/;
        return passwordRegex.test(password);
    }

    // 修改密码函数 - 统一处理账户管理表单和模态框
    function changePassword(formId) {
        // 获取表单元素
        const form = document.getElementById(formId);
        if (!form) {
            console.error('找不到表单:', formId);
            return;
        }

        // 获取表单值
        const currentPassword = form.querySelector('[name="current-password"]').value;
        const newPassword = form.querySelector('[name="new-password"]').value;
        const confirmPassword = form.querySelector('[name="confirm-password"]').value;

        // 验证当前密码是否为空
        if (!currentPassword) {
            showNotification('错误', '请输入当前密码', 'danger');
            return;
        }

        // 检查新密码是否匹配
        if (newPassword !== confirmPassword) {
            showNotification('错误', '两次输入的密码不一致', 'danger');
            return;
        }

        // 密码强度验证
        if (!validatePassword(newPassword)) {
            showNotification('错误', '密码至少需要8个字符，包含字母和数字', 'danger');
            return;
        }

        // 显示加载状态
        const submitBtn = form.querySelector('button[type="submit"]');
        const originalText = submitBtn.innerHTML;
        submitBtn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> 处理中...';
        submitBtn.disabled = true;

        // 创建表单数据（使用URL编码格式）
        const formData = {
            'current-password': currentPassword,
            'new-password': newPassword,
            'confirm-password': confirmPassword
        };

        // 转换为URL编码字符串
        const encodedData = Object.keys(formData)
            .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(formData[key])}`)
            .join('&');

        // 发送请求
        fetch('TeacherChangePasswordServlet', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
            },
            credentials: 'include',
            body: encodedData
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showNotification('成功', data.message, 'success');
                    form.reset();

                    // 如果是模态框，关闭它
                    if (formId === 'modal-password-form') {
                        document.getElementById('change-password-modal').classList.add('hidden');
                    }

                    // 延迟跳转到登录页面
                    setTimeout(() => {
                        window.location.href = 'teacher_student.jsp';
                    }, 1500);
                } else {
                    showNotification('错误', data.message, 'danger');
                }
            })
            .catch(error => {
                console.error('修改密码失败:', error);
                showNotification('错误', '修改密码失败，请重试', 'danger');
            })
            .finally(() => {
                submitBtn.innerHTML = originalText;
                submitBtn.disabled = false;
            });
    }

    // 加载成绩管理所需的班级列表
    function loadGradeClasses() {
        fetch('ClassListServlet')
            .then(response => response.json())
            .then(data => {
                const gradeClassSelect = document.getElementById('grade-class');
                gradeClassSelect.innerHTML = '<option value="">请选择班级</option>';

                data.forEach(cls => {
                    const option = document.createElement('option');
                    option.value = cls.class_id;
                    option.textContent = cls.class_name;
                    gradeClassSelect.appendChild(option);
                });
            })
            .catch(error => {
                console.error('加载班级列表失败:', error);
                showNotification('错误', '加载班级列表失败', 'danger');
            });
    }

    // 根据班级加载考试列表
    function loadExamsForClass(classId) {
        if (!classId) return;

        fetch(`ClassExamsServlet?classId=${classId}`)
            .then(response => response.json())
            .then(exams => {
                const examSelect = document.getElementById('grade-exam');
                examSelect.innerHTML = '<option value="">请选择考试</option>';

                exams.forEach(exam => {
                    const option = document.createElement('option');
                    option.value = exam.exam_id;
                    option.textContent = exam.exam_name;
                    examSelect.appendChild(option);
                });
            })
            .catch(error => {
                console.error('加载考试列表失败:', error);
                showNotification('错误', '加载考试列表失败', 'danger');
            });
    }

    // 查看班级成绩
    function viewClassGrades(classId, examId) {
        fetch(`GradeViewServlet?type=class&class_id=${classId}&exam_id=${examId}`)
            .then(response => response.json())
            .then(grades => {
                const gradesResult = document.getElementById('grades-result');
                const gradesTitle = document.getElementById('grades-title');
                const gradesHeader = document.getElementById('grades-header');
                const gradesBody = document.getElementById('grades-body');

                // 显示成绩结果区域
                gradesResult.classList.remove('hidden');
                gradesTitle.textContent = `${document.getElementById('grade-class').options[document.getElementById('grade-class').selectedIndex].text} - ${document.getElementById('grade-exam').options[document.getElementById('grade-exam').selectedIndex].text} 成绩表`;

                // 构建表头
                gradesHeader.innerHTML = `
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">学号</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">姓名</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">成绩</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">是否通过</th>
                `;

                // 构建表格内容
                gradesBody.innerHTML = '';
                grades.forEach(grade => {
                    const row = document.createElement('tr');
                    row.className = 'table-row';
                    row.innerHTML = `
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm font-medium text-gray-900">${grade.student_no}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-900">${grade.name}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-900">${grade.score || '未评分'}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="px-2 py-1 text-xs rounded-full ${grade.is_passed == '通过' ? 'bg-success text-white' : 'bg-warning text-white'}">${grade.is_passed || '未评分'}</span>
                        </td>
                    `;
                    gradesBody.appendChild(row);
                });
            })
            .catch(error => {
                console.error('获取班级成绩失败:', error);
                showNotification('错误', '获取班级成绩失败', 'danger');
            });
    }

    // 查看学生成绩
    function viewStudentGrades(keyword) {
        fetch(`GradeViewServlet?type=student&keyword=${encodeURIComponent(keyword)}`)
            .then(response => response.json())
            .then(grades => {
                const gradesResult = document.getElementById('grades-result');
                const gradesTitle = document.getElementById('grades-title');
                const gradesHeader = document.getElementById('grades-header');
                const gradesBody = document.getElementById('grades-body');

                // 显示成绩结果区域
                gradesResult.classList.remove('hidden');
                gradesTitle.textContent = `学生成绩查询结果: ${keyword}`;

                // 构建表头
                gradesHeader.innerHTML = `
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">课程</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">成绩</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">是否通过</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">提交时间</th>
                `;

                // 构建表格内容
                gradesBody.innerHTML = '';
                if (grades.length === 0) {
                    gradesBody.innerHTML = '<tr><td colspan="4" class="px-6 py-4 text-center text-sm text-gray-500">没有找到相关成绩记录</td></tr>';
                    return;
                }

                grades.forEach(grade => {
                    const row = document.createElement('tr');
                    row.className = 'table-row';
                    row.innerHTML = `
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm font-medium text-gray-900">${grade.course_name}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-900">${grade.score || '未评分'}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="px-2 py-1 text-xs rounded-full ${grade.is_passed == '通过' ? 'bg-success text-white' : 'bg-warning text-white'}">${grade.is_passed || '未评分'}</span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-500">${grade.submit_time || '--'}</div>
                        </td>
                    `;
                    gradesBody.appendChild(row);
                });
            })
            .catch(error => {
                console.error('获取学生成绩失败:', error);
                showNotification('错误', '获取学生成绩失败', 'danger');
            });
    }

    // 获取状态文本
    function getStatusText(status) {
        switch (status) {
            case 0: return "申请中";
            case 1: return "已批准";
            case 2: return "已激活";
            case 3: return "已结束";
            case 4: return "已取消";
            default: return "未知状态";
        }
    }

    // 获取状态类
    function getStatusClass(status) {
        switch (status) {
            case 0: return "bg-warning text-white";
            case 1: return "bg-success text-white";
            case 2: return "bg-primary text-white";
            case 3: return "bg-gray-500 text-white";
            case 4: return "bg-danger text-white";
            default: return "bg-gray-500 text-white";
        }
    }

    // 显示通知
    function showNotification(title, message, type) {
        const notification = document.getElementById('notification');
        const notificationIcon = document.getElementById('notification-icon');
        const notificationTitle = document.getElementById('notification-title');
        const notificationMessage = document.getElementById('notification-message');

        // 设置通知样式
        notificationIcon.className = `flex-shrink-0 h-6 w-6 flex items-center justify-center rounded-full ${type == 'success' ? 'bg-green-100 text-green-500' : type == 'danger' ? 'bg-red-100 text-red-500' : 'bg-blue-100 text-blue-500'}`;
        notificationIcon.innerHTML = type == 'success' ? '<i class="fa fa-check"></i>' : type == 'danger' ? '<i class="fa fa-times"></i>' : '<i class="fa fa-info"></i>';
        notificationTitle.textContent = title;
        notificationMessage.textContent = message;

        // 显示通知
        notification.classList.remove('translate-x-full');

        // 5秒后自动隐藏
        setTimeout(() => {
            notification.classList.add('translate-x-full');
        }, 5000);
    }

    // 初始化图表
    function initCharts(data) {
        // 考试安排图表
        const scheduleCtx = document.getElementById('examScheduleChart').getContext('2d');
        new Chart(scheduleCtx, {
            type: 'bar',
            data: {
                labels: data.recentExams.map(exam => exam.exam_name),
                datasets: [{
                    label: '考试状态',
                    data: data.recentExams.map(exam => exam.status),
                    backgroundColor: data.recentExams.map(exam => {
                        switch (exam.status) {
                            case 0: return '#FF7D00';
                            case 1: return '#00B42A';
                            case 2: return '#165DFF';
                            case 3: return '#86909C';
                            default: return '#722ED1';
                        }
                    }),
                    borderRadius: 6
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            precision: 0
                        }
                    }
                }
            }
        });

        // 课程分布饼图
        const courseCtx = document.getElementById('courseDistributionChart').getContext('2d');
        new Chart(courseCtx, {
            type: 'doughnut',
            data: {
                labels: data.teachingCourses.map(course => course.course_name),
                datasets: [{
                    label: '课程分布',
                    data: data.teachingCourses.map(course => 1), // 每个课程计数为1
                    backgroundColor: ['#165DFF', '#0FC6C2', '#722ED1', '#FF7D00', '#F53F3F'],
                    borderWidth: 0
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        position: 'bottom'
                    }
                }
            }
        });
    }

    // 模态框事件处理
    function setupModalEvents() {
        // 修改密码模态框
        document.getElementById('change-password-btn').addEventListener('click', function() {
            document.getElementById('change-password-modal').classList.remove('hidden');
        });
        document.getElementById('close-password-modal').addEventListener('click', function() {
            document.getElementById('change-password-modal').classList.add('hidden');
        });
        document.getElementById('cancel-password-btn').addEventListener('click', function() {
            document.getElementById('change-password-modal').classList.add('hidden');
        });

        // 关闭通知
        document.getElementById('close-notification').addEventListener('click', function() {
            document.getElementById('notification').classList.add('translate-x-full');
        });
    }
</script>
</body>
</html>